# management/models.py

from datetime import datetime

from django.db import models
from django.utils.safestring import mark_safe 
from django.contrib.gis.db import models #导入Geodjango模块
from users.models import UserProfile
from DjangoUeditor.models import UEditorField

class ItemClass(models.Model):
    '''
    日常管理分类
    '''
    name = models.CharField(max_length=50, verbose_name='分类名称')
    desc = models.CharField(max_length=100, verbose_name='分类描述',blank=True)
    sort = models.IntegerField(default=0, verbose_name='排序值')
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children', verbose_name='上级分类',
                               limit_choices_to={'is_abort': False, 'is_root': True},on_delete=models.CASCADE)
    is_root = models.BooleanField(default=False, verbose_name='是否是一级分类')
    is_abort = models.BooleanField(default=False, verbose_name='是否删除')

    class Meta:
        verbose_name = '日常管理分类'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

class ContentList(models.Model):
    '''
    管理事项列表
    '''
    name = models.CharField(max_length=255, verbose_name='题目/标题')
    itemclassid = models.ForeignKey(ItemClass,verbose_name='管理分类',on_delete=models.DO_NOTHING)
    content = models.TextField(verbose_name='主要内容',null=True, blank=True)
    peoples = models.CharField(blank=True,max_length=255, verbose_name='相关人员')
    publish_time = models.DateTimeField(blank=True,verbose_name='发生时间')
    add_time = models.DateTimeField('添加时间',auto_now_add=True)
    update_time = models.DateTimeField('最后更新时间',auto_now=True)

    def filelist_col(self):#添加相关文件列表列
        '''
        1.文件名称+url
        '''
        html=''
        i = 0
        sub_col_name_list = FileList.objects.filter(contentlistid=self.pk)
        for sub_col in sub_col_name_list:
            i +=1
            html += "%d.<a href='/media/%s'>%s</a><br>" %(i,sub_col.url,sub_col.name)
        html += '<a href="/xadmin/management/filelist/add/?_rel_contentlistid__id__exact='+str(self.pk)+'">上传文件</a>'
        return mark_safe(html)
    filelist_col.short_description = '相关文件'

    class Meta:
        verbose_name = '事项清单'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name

class FileList(models.Model):
    name = models.CharField(max_length=255,verbose_name='文件名')
    contentlistid = models.ForeignKey(ContentList,verbose_name='事项名称',on_delete=models.DO_NOTHING)
    url = models.FileField(verbose_name='文件地址',upload_to='management/',null=False,blank=True)
    add_time = models.DateTimeField('上传时间',auto_now_add=True)
    class Meta:
        verbose_name = '相关附件'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name
